package io.github.wslxm.springbootplus2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.io.IOException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

@Configuration
public class LocaleConfig implements WebMvcConfigurer {

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();
        Set<String> baseNames = new HashSet<>();
        // 使用 PathMatchingResourcePatternResolver 加载所有 jar 下的匹配的语言文件
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(new DefaultResourceLoader());
        Resource[] resources = new Resource[0];
        try {
            resources = resolver.getResources("classpath*:/i18n/**/language_*.properties");
            for (Resource resource : resources) {
                // 获取资源文件的路径
                String path = resource.getURL().getPath(); // 获取资源文件的 URL 路径
                String[] i18ns = path.split("i18n/");
                String i18nUri = i18ns[1];
                String[] i18nUris = i18nUri.split("/");
                // 构造完整的 basename 路径
                baseNames.add("classpath:i18n/" + i18nUris[0] + "/language");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 设置多个基本名称
        baseNames.add("classpath:i18n/language");
        String[] baseNameArray = baseNames.toArray(new String[0]);
        source.setBasenames(baseNameArray);
        // 设置消息文件的编码
        source.setDefaultEncoding("UTF-8");
        return source;
    }

    @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
        resolver.setDefaultLocale(Locale.ENGLISH); // 设置默认语言 ENGLISH CHINESE
        return resolver;
    }
}
